import { ComponentState } from 'react'
import { ComponentInfo } from './types'

export function getNextSelectedId(fe_id: string, componentList: Array<ComponentInfo>) {
  componentList = componentList.filter(c => !c.isHidden)

  const index = componentList.findIndex(c => c.fe_id === fe_id)

  if (index < 0) return ''

  let newSelectedId = ''
  const length = componentList.length
  if (length <= 1) {
    newSelectedId = ''
  } else {
    if (index + 1 === length) {
      newSelectedId = componentList[index - 1].fe_id
    } else {
      newSelectedId = componentList[index + 1].fe_id
    }
  }

  return newSelectedId
}

export function insertNewComponent(draft: ComponentState, newComponent: ComponentInfo) {
  const { selectedId, componentList } = draft

  if (!selectedId) {
    draft.componentList.push(newComponent)
  } else {
    const selectedIdIndex = componentList.findIndex((c: ComponentInfo) => c.fe_id === selectedId)
    draft.componentList.splice(selectedIdIndex + 1, 0, newComponent)
  }

  draft.selectedId = newComponent.fe_id
}
